package com.fx.controller;

import javafx.application.Platform;
import java.util.concurrent.Semaphore;
 
public class Advancer{
    private boolean able;
    private Updatable worker;
 
    public Advancer(Updatable worker){
        able = false;
        this.worker = worker;
    }
 
    public final synchronized void advance(Updatable renderer){
        if(able)return;//防止启动多个线程
        able = true;
        new Thread(()->{
            long timer = System.nanoTime();
            Semaphore semaphore = new Semaphore(2);
            while(able)try{
                //计算瞬间时间
                long now = System.nanoTime();
                double moment = (now - timer) * 0.000000001;
                timer = now;
                //处理事务
                worker.update(moment);
                semaphore.acquire();
                Platform.runLater(()->{
                    renderer.update(moment);
                    semaphore.release();
                });
            }catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
 
    //记得熄火，不过线程不会马上退出。
    public final void misfire(){
        able = false;
    }
}